from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView

from account.models import Profile
from config import settings
from utils.zhifubao import Alipay
from utils.common import get_random_code
from .models import Card, Order
from .permissions import IsAdminUserOrReadOnly
from .serializers import CardSerializer, OrderSerializer
from django.utils import timezone
from datetime import datetime


# Create your views here.
class CardViewSet(viewsets.ModelViewSet):
    queryset = Card.objects.all()
    serializer_class = CardSerializer
    permission_classes = [IsAdminUserOrReadOnly, ]


class AlipayAPIView(APIView):
    def get(self, request):
        """
        发起支付宝支付,有2种场景
        1.创建新支付
        2.支付未完成的订单
        """
        card_id = request.GET.get('card_id', None)
        try:
            card = Card.objects.get(pk=card_id)
        except:
            return Response({'message': '会员卡参数错误'})
        order_sn = request.GET.get('order_sn', None)
        if not order_sn:
            out_trade_no = "pay" + datetime.now().strftime("%Y%m%d%H%M%S") + get_random_code(4)
            # 创建订单
            try:
                # 这里有一点问题
                Order.objects.create(
                    profile=Profile.objects.get(user=request.user),
                    card=card,
                    order_sn=out_trade_no,
                    order_mount=card.card_price,
                    pay_time=timezone.now()  # 2023-09-13 15:32:58.148725+09:00
                )
            except:
                return Response({'message': '订单创建失败'})
        else:
            try:
                order = Order.objects.get(order_sn=order_sn)
                if order.pay_status != 'PAYING':
                    return Response('创建相关')
                out_trade_no = order_sn
            except:
                return Response('you sn')
        # 请求支付
        try:
            alipay = Alipay()
            pay_url = alipay.trade_page(out_trade_no, str(card.card_price), card.card_name, '支付宝支付',
                                        'FAST_INSTANT_TRADE_PAY')
            return Response(pay_url)
        except Exception as e:
            print(e)
            return Response('支付失败')


class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer


class AlipayCallbackAPIView(APIView):
    def post(self, request):
        params = request.POST.dict()
        print(params)
        # 去除sign 和 sign_type
        sign = params.pop('sign')
        del params['sign_type']
        # 对字典进行排序
        sorted_list = sorted([(k, v) for k, v in params.items()])
        unsigned_string = '&'.join(f"{k}={v}" for k, v in sorted_list)  # buyer_pay_amount=0.02&app_id=9021000126620710
        alipay = Alipay()
        if not alipay.verify_sign(unsigned_string, sign):
            print('vefify sign error')
            return Response('error')
        # 验证out_trade_no
        try:
            order = Order.objects.get(order_sn=params.get('out_trade_no'))
        except:
            return Response('error')
        if params.get('total_amount') != str(order.order_mount):
            return Response('error')
        if params.get('seller_id') != settings.ALIPAY_SELLER_ID:
            return Response('error')
        if params.get('app_id') != settings.ALIPAY_APP_ID:
            return Response('error')
        if params.get('trade_status') not in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
            return Response('error')
        # 业务逻辑
        print('全部验证通过')
        return Response('success')


from .tasks import add, mul, xsum


class TaskAPIView(APIView):

    def get(self, request):
        result1 = add.delay(3, 4)
        print(f'add : {result1}')

        result2 = mul.delay(4, 5)
        print(f'mul: {result2}')

        result3 = xsum.delay([1, 2, 3])
        print(f'xsum: {result3}')

        return Response('执行task')
